package com.water.camera.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.water.camera.activity.PinAct;
import com.water.camera.bean.EditItem;
import com.water.camera.databinding.TemplateItemBinding;

import java.util.ArrayList;

public class PinWordAdapter extends RecyclerView.Adapter {

    ArrayList<EditItem> list = new ArrayList<>();
    PinAct act;

    public PinWordAdapter(PinAct act) {
        this.act = act;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        TemplateItemBinding binding = TemplateItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class Holder extends RecyclerView.ViewHolder {
        TemplateItemBinding binding;

        Holder(TemplateItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            EditItem item = list.get(p);
            binding.title.setText(item.name);
            binding.desc.setText(item.value);
            itemView.setOnClickListener(v -> act.toEdit(item, p));
        }
    }

    public void append(EditItem item) {
        if (item == null) {
            return;
        }
        list.add(item);
        notifyItemInserted(list.size() - 1);
    }

    public void update(EditItem item, int p) {
        EditItem tmp = list.get(p);
        tmp.name = item.name;
        tmp.value = item.value;
        notifyItemChanged(p);
    }
}
